import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:gzmall_app/common/api.dart';
import 'package:gzmall_app/common/color_common.dart';
import 'package:gzmall_app/common/net_util.dart';
import 'package:gzmall_app/common/toast_util.dart';
import 'package:gzmall_app/mine/select_regions.dart';
import 'package:gzmall_app/model/regions.dart';
import 'package:gzmall_app/model/address.dart';
import 'package:dio/dio.dart';

class AddressAddPage extends StatefulWidget {
  Address address;

  AddressAddPage({
    this.address,
  });

  @override
  State<StatefulWidget> createState() {
    return AddressAddPageState(address: address);
  }
}

class AddressAddPageState extends State<AddressAddPage> {
  String _name, _phone, _area, _address, _provinceId, _cityId, _districtId;
  bool _isDefaultAddress = false;

  Address address;

  TextEditingController _nameController, _phoneController, _addressController;

  AddressAddPageState({
    this.address,
  });

  @override
  void initState() {
    super.initState();
    _nameController = TextEditingController();
    _phoneController = TextEditingController();
    _addressController = TextEditingController();
    _initAddress();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _createAppBar(),
      body: Container(
        color: ColorCommon.grey5,
        child: ListView(
          children: <Widget>[
            Row(children: <Widget>[
              Expanded(
                child: SizedBox(
                  height: 130.0,
                  child: Column(children: <Widget>[
                    Expanded(
                      child: _getInputView("收货人:", "", (str) {
                        _name = str ?? '';
                      }, _nameController),
                    ),
                    SizedBox(
                      height: 1.0,
                    ),
                    Expanded(
                      child: _getInputView("手机号码:", "", (str) {
                        _phone = str ?? '';
                      }, _phoneController),
                    ),
                  ]),
                ),
              ),
              // Container(
              //     color: Colors.white,
              //     width: 130.0,
              //     height: 130.0,
              //     margin: const EdgeInsets.only(left: 1.0, bottom: 1.0),
              //     child: Column(
              //       mainAxisAlignment: MainAxisAlignment.center,
              //       children: <Widget>[
              //         Icon(
              //           Icons.account_circle,
              //           size: 40.0,
              //         ),
              //         Padding(
              //           padding: const EdgeInsets.only(top: 10.0),
              //           child: Text("选联系人"),
              //         ),
              //       ],
              //     )),
            ]),
            GestureDetector(
              onTap: () {
                Navigator.of(context).push(MaterialPageRoute(builder: (_) {
                  return SelectRegionsPage();
                })).then((value) {
                  if (value != null) {
                    Regions r1 = Regions.fromJson(value["1"]);
                    Regions r2 = Regions.fromJson(value["2"]);
                    Regions r3 = Regions.fromJson(value["3"]);
                    if (!mounted) return;
                    setState(() {
                      _provinceId = r1.id.toString();
                      _cityId = r2.id.toString();
                      _districtId = r3.id.toString();
                      _area = r1.value + r2.value + r3.value;
                    });
                  }
                });
              },
              child: Container(
                color: Colors.white,
                height: 65.0,
                padding: const EdgeInsets.only(right: 15.0),
                child: Row(children: <Widget>[
                  Expanded(
                    child: Container(
                      color: Colors.white,
                      padding: const EdgeInsets.only(left: 15.0),
                      child: Row(children: <Widget>[
                        Padding(
                          padding: const EdgeInsets.only(right: 10.0),
                          child: Text(
                            "所在地区:",
                            style: TextStyle(color: ColorCommon.black1),
                          ),
                        ),
                        Expanded(
                          child: Text(_area ?? ""),
                        ),
                      ]),
                    ),
                  ),
                  new Image.asset(
                    "images/right_arrow.png",
                    width: 10.0,
                    height: 10.0,
                  ),
                ]),
              ),
            ),
            Container(
              color: Colors.white,
              height: 100.0,
              margin: const EdgeInsets.only(top: 1.0, bottom: 1.0),
              padding: const EdgeInsets.only(top: 10.0, bottom: 10.0),
              child: Row(
                children: <Widget>[
                  Expanded(
                    child: _getInputView("详细地址:", "街道，楼牌号等", (str) {
                      _address = str ?? '';
                    }, _addressController),
                  ),
                  // Container(
                  //   height: 100.0,
                  //   padding: const EdgeInsets.only(left: 10.0, right: 10.0),
                  //   child: Icon(Icons.voice_chat),
                  // )
                ],
                crossAxisAlignment: CrossAxisAlignment.start,
              ),
            ),
            // Container(
            //   color: Colors.white,
            //   padding: const EdgeInsets.only(
            //       left: 15.0, right: 15.0, top: 10.0, bottom: 10.0),
            //   child: Row(
            //     children: <Widget>[
            //       Padding(
            //         padding: const EdgeInsets.only(right: 40.0),
            //         child: Text(
            //           "标签:",
            //           style: TextStyle(color: ColorCommon.black1),
            //         ),
            //       ),
            //       Column(
            //         crossAxisAlignment: CrossAxisAlignment.start,
            //         children: <Widget>[
            //           Wrap(
            //             spacing: 10.0,
            //             children: <Widget>[
            //               _getTagView("家"),
            //               _getTagView("公司"),
            //               _getTagView("学校"),
            //             ],
            //           ),
            //           Wrap(
            //             children: <Widget>[
            //               _getTagView("+"),
            //             ],
            //           ),
            //         ],
            //       ),
            //     ],
            //   ),
            // ),
            Container(
              color: Colors.white,
              padding: const EdgeInsets.all(15.0),
              margin: const EdgeInsets.only(top: 1.0),
              child: Row(
                children: <Widget>[
                  Expanded(
                    child: Text(
                        "设置默认地址\n提醒: 每次下单时会使用改地址(轻松购下单除外)\n实际下单地址会根据您购物切换的地区进行只能判断\n请在下单时确认哦"),
                  ),
                  CupertinoSwitch(
                    value: _isDefaultAddress,
                    onChanged: (isCheck) {
                      if (!mounted) return;
                      setState(() {
                        _isDefaultAddress = isCheck;
                      });
                    },
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  _createAppBar() {
    return AppBar(
      elevation: 0.0,
      title: Text("新建收货人"),
      leading: IconButton(
        icon: Icon(Icons.arrow_back_ios),
        onPressed: () {
          Navigator.of(context).pop();
        },
      ),
      actions: <Widget>[
        InkWell(
          onTap: () {
            _saveAction();
          },
          child: Container(
            child: Text("保存"),
            alignment: Alignment.center,
            padding: const EdgeInsets.only(right: 15.0),
          ),
        ),
      ],
    );
  }

  _getInputView(String tips, String hint, Function onChanged,
      TextEditingController controller) {
    return Container(
      color: Colors.white,
      padding: const EdgeInsets.only(left: 15.0),
      child: Row(children: <Widget>[
        Padding(
          padding: const EdgeInsets.only(right: 10.0),
          child: Text(
            tips,
            style: TextStyle(color: ColorCommon.black1),
          ),
        ),
        Expanded(
          child: TextField(
            controller: controller,
            style: TextStyle(color: ColorCommon.black1),
            decoration: InputDecoration.collapsed(
              hintText: hint,
            ),
            onChanged: onChanged,
          ),
        ),
      ]),
    );
  }

  _getTagView(String content) {
    return Chip(
      backgroundColor: Colors.white,
      label: SizedBox(
        width: 50.0,
        child: Text(
          content,
          textAlign: TextAlign.center,
        ),
      ),
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(100.0),
          side: BorderSide(color: ColorCommon.grey5, width: 1.0)),
    );
  }

  _initAddress() {
    if (address != null) {
      _name = address.sendee != null && address.sendee.isNotEmpty
          ? address.sendee
          : "";
      _phone = address.phone != null && address.phone.isNotEmpty
          ? address.phone
          : "";
      _area = address.province != null &&
              address.city != null &&
              address.district != null
          ? address.province + address.city + address.district
          : "";
      _address = address.address != null && address.address.isNotEmpty
          ? address.address
          : "";
      _isDefaultAddress = address.isDefault;

      _provinceId = address.provinceId.toString();
      _cityId = address.cityId.toString();
      _districtId = address.districtId.toString();
    }
  }

  _saveAction() {
    if (_name == null || _name.isEmpty) {
      ToastUtil.showMessageToast("请输入收货人姓名");
      return;
    }
    if (_phone == null || _phone.isEmpty) {
      ToastUtil.showMessageToast("请输入手机号码");
      return;
    }
    if (_area == null || _area.isEmpty) {
      ToastUtil.showMessageToast("请选择所在地区");
      return;
    }
    if (_address == null || _address.isEmpty) {
      ToastUtil.showMessageToast("请输入详细地址");
      return;
    }

    if (address != null) {
      _updateAddress(address.id, _name, _phone, _address, _isDefaultAddress,
          _provinceId, _cityId, _districtId);
    } else {
      _saveAddress(_name, _phone, _address, _isDefaultAddress, _provinceId,
          _cityId, _districtId);
    }
  }

  _saveAddress(String name, String phone, String address, bool isDefault,
      String provinceId, String cityId, String districtId) {
    FormData formData = new FormData.fromMap({
      "address[phone]": phone,
      "address[sendee]": name,
      "address[address]": address,
      "address[is_default]": isDefault.toString(),
      "address[province_id]": provinceId,
      "address[city_id]": cityId,
      "address[district_id]": districtId,
    });

    NetUtil.post(context, Api.addresses, (data, message) {
      ToastUtil.showMessageToast(message);
      Navigator.of(context).pop();
    }, params: formData, isShowLoading: true);
  }

  _updateAddress(int id, String name, String phone, String address,
      bool isDefault, String provinceId, String cityId, String districtId) {
    FormData formData = new FormData.fromMap({
      "address[phone]": phone,
      "address[sendee]": name,
      "address[address]": address,
      "address[is_default]": isDefault.toString(),
      "address[province_id]": provinceId,
      "address[city_id]": cityId,
      "address[district_id]": districtId,
    });

    NetUtil.put(
      context,
      Api.addresses + "/" + id.toString(),
      (data, message) {
        ToastUtil.showMessageToast(message);
        Navigator.of(context).pop();
      },
      params: formData,
    );
  }
}
